<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 消息提示框部分 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条部分 active当前绑定的项  减0是将字符串转换为数字-->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏标签部分 使用1...4可以与activeIndex使用一组数据不需要再转换-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!--options数据 props配置数据源 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                :cateList="{ expandTrigger: 'hover' }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 参数列表渲染表单item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cd"
                  v-for="(cd, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 并没有调用axios字段，需要手动配置token -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">商品内容
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="preivewVisible"
      width="50%"
    >
      <img :src="previewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'

export default {
  name: 'add',
  data() {
    return {
      //将步骤条与表单tab标签同步展示
      activeIndex: '0',
      //添加表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //商品分类选择
        goods_cat: [],
        //存放图片数组
        pics: [],
        //富文件内容-填入介绍
        goods_introduce: '',
        //表单填写的属性数组
        attrs:[]
      },
      addFormRules: {
        goods_name: [
          { required: 'true', message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: 'true', message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_number: [
          { required: 'true', message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_weight: [
          { required: 'true', message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: 'true', message: '请选择商品类型', trigger: 'blur' },
        ],
      },
      //商品分类列表
      cateList: [],
      //级联选择器配置数据源
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      //级联选择器选择的key
      selectKeys: [],
      // 级联选择器的校验规则
      goods_cat: [],
      //动态参数列表数据
      manyTableData: [],
      //静态参数列表数据l
      onlyTableData: [],
      //图片上传地址
      uploadURL: 'http://175.27.228.178:3434/api/private/v1/upload',
      //为每次上传数据的请求头添加一个token
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      //预览图片地址
      previewPath:'',
      //图片预览对话框显示与隐藏
      preivewVisible:false,
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    //获取所有商品数据
    async getGoodsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
      return this.$message.success('获取数据成功')
    },
    //当级联选择器选择发生变化
    handleChange() {
      // console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    //监听tab标签是否选择三级分类且切换标签
    beforeTabLeave(activeName, oldActiveName) {
      // console.log('即将进入的标签' + activeName)
      // console.log('即将离开的标签'+oldActiveName)
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    //当点击tab栏时触发
    async tabClicked() {
      // console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        // console.log('动态参数面板')
        //数据库获取当前联级下的标签的参数列表
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数列表失败')
        }
        this.$message.success('获取动态参数列表成功')
        // console.log(res.data)
        //分割字符串为数组 循环attr_vals如果长度为0则返回空若不为0则分割字符串
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        console.log(this.manyTableData)
      }
      //获取静态属性列表
      else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'only' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态参数列表失败')
        }
        this.onlyTableData = res.data
        this.$message.success('获取静态参数列表成功')
        
        // console.log(res.data)
      }
    },
    //图片预览事件
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      console.log(this.previewPath)
      this.preivewVisible=true
    },
    //图片移除事件
    handleRemove(file) {
      const filePath = file.response.data.tem_path

      // 02从数组中找到相应的
      const i = this.addForm.pics.indexOf((x) => x.pic === filePath)
      // 03将数据从数组中移除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 图片上传成功后，获取response
    handleSuccess(response) {
      // console.log(response)
      //01拼接得到图片信息
      const picInfo = { pic: response.data.tmp_path }
      //02将图片信息拼接到数组中
      this.addForm.pics.push(picInfo)
      // console.log(picInfo)
    },
    //
    add() {
      // console.log(this.addForm)
      this.$refs.addFormRef.validate( async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单数据')
        }
        //执行添加的业务逻辑 ！！！！深拷贝，防止数据冲突
        const form = _.cloneDeep(this.addForm)
        console.log(form)
        form.goods_cat=form.goods_cat.join(',')

        //处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        //处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)

        //发起请求添加商品
        const { data: res } = await this.$http.post(`goods`, form)
        if (res.meta.status !== 201) {
          console.log(res.meta.msg)
          return this.$message.error('商品添加失败'+','+res.meta.msg)
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg{
  width: 100%;
}

.btnAdd{
  margin-top: 15px;
}
</style>
